package han.message;

import han.entity.*;
import han.module.index.IndexSolr;
import han.proof.GroupDetailInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;

import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/7/20 15:46
 * @dscription: 消息队列处理器
 */
public class MessageProcessor implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(MessageProcessor.class);
    /**
     * 线程安全的消息队列
     */
    private LinkedBlockingQueue<MessageEntity> messageQueue;
    /**
     * 是否继续运行
     */
    private boolean isRunning;
    /**
     * 群组详情
     */
    private GroupDetailInfo groupDetailInfo;
    /**
     * 索引对象
     */
    private IndexSolr indexSolr;

    public MessageProcessor(LinkedBlockingQueue<MessageEntity> messageQueue) {
        this.messageQueue = messageQueue;
        isRunning = true;
        groupDetailInfo = GroupDetailInfo.getInstance();
        indexSolr = IndexSolr.getIndexSolrInstance();
    }

    @Override
    public void run() {
        logger.info("消息队列处理器启动");
        while (isRunning) {
            try {
                MessageEntity messageEntity = messageQueue.take();
                NeedFetchUrlEntity needFetchUrlEntity = showMessage(messageEntity);
                printlnInfo(needFetchUrlEntity);
                /*if (Objects.isNull(needFetchUrlEntity)) {
                    //如果上传对象为null,则不上传
                    continue;
                }
                boolean isSucceed = indexSolr.sendToIndex(needFetchUrlEntity);
                if (isSucceed) {
                    logger.info("索引添加成功:" + needFetchUrlEntity);
                } else {
                    logger.error("索引添加失败:" + needFetchUrlEntity);
                }*/
            } catch (InterruptedException e) {
                logger.info(e.toString());
                StackTraceElement[] stackTraceElements = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    logger.error(stackTraceElement.toString());
                }
            }
        }
        logger.info("消息队列处理器停止");
    }

    /**
     * 处理消息
     *
     * @param entity 消息实体
     */
    private NeedFetchUrlEntity showMessage(MessageEntity entity) {

        NeedFetchUrlEntity needFetchUrlEntity = new NeedFetchUrlEntity();
        try {
            String content = entity.getContent();
            if (content.isEmpty()) {
                //如果内容为空,返回
                return null;
            }
            long uin = entity.getUin();
            long fromUin = entity.getFromUin();

            GroupEntity groupEntity = groupDetailInfo.getGroupEntity(uin + "");
            long groupAccount = -1;
            try {
                groupAccount = groupEntity.getGroupAccount();
            } catch (NullPointerException e) {
                logger.error("没有获取到群号" + groupEntity);
            }
            String groupName = groupEntity.getName();
            String name = "-";
            long account = -1;
            try {
                Map<String, GroupMemberEntity> map = groupEntity.getMemberMap();
                GroupMemberEntity memberEntity = map.get(fromUin + "");
                name = memberEntity.getNickName();
                account = memberEntity.getAccount();
            } catch (NullPointerException ignore) {
            } catch (Exception e) {
                logger.info(e.toString());
                StackTraceElement[] stackTraceElements = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    logger.error(stackTraceElement.toString());
                }
            }
            needFetchUrlEntity.setAuthor(name);
            needFetchUrlEntity.setAuthorUrlS(account + "");
            needFetchUrlEntity.setTitle(groupName);
            needFetchUrlEntity.setHostId(groupAccount);
            needFetchUrlEntity.setText(content);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = simpleDateFormat.format(entity.getTime() * 1000);
            needFetchUrlEntity.setTime(time);
        } catch (Exception e) {
            logger.info(e.toString());
            StackTraceElement[] stackTraceElements = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTraceElements) {
                logger.error(stackTraceElement.toString());
            }
        }
        return needFetchUrlEntity;
    }

    /**
     * 停止消息队列处理器,为了防止因阻塞造成的无法停止,先放入一个,在将标志位设置为false
     */
    public void close() {
        try {
            messageQueue.put(new GroupMessageEntity("", "", 0, 0, 0, 0, 0, 0));
        } catch (InterruptedException e) {
            logger.info(e.toString());
            StackTraceElement[] stackTraceElements = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTraceElements) {
                logger.error(stackTraceElement.toString());
            }
        }
        isRunning = false;
    }
}
